#include <bits/stdc++.h>

using namespace std;

string mg[1010];
int n,m,ans[100010],color;
int hasvis[1010][1010];
int xx[] = {1,-1,0,0};
int yy[] = {0,0,-1,1};
struct node{
    int x;
    int y;
    int s;
}node1;
void f(int a,int b){
    queue <node> q;
    node1.x = a;
    node1.y = b;
    node1.s = 1;
    q.push(node1);
    hasvis[a][b]=color;
    while(!q.empty()){
        node t = q.front();
        ans[color]++;
        for(int i=0;i<4;i++){
            int dx = t.x+xx[i];
            int dy = t.y+yy[i];
            if(dx>=1&&dx<=n&&dy>=1&&dy<=n&&mg[t.x-1][t.y-1]!=mg[dx-1][dy-1]&&!hasvis[dx][dy])
               {
                   node tt;
                   tt.x = dx;
                   tt.y = dy;
                   tt.s = t.s+1;
                   hasvis[dx][dy]=color;
                   q.push(tt);
               }
            }
        q.pop();
    }
}
int main()
{
    cin>>n>>m;
    for(int i = 0; i<n ; i++){
        cin>>mg[i];
    }
    for(int i =0 ;i<m ;i++){
        int a,b;
        cin>>a>>b;
        if(!hasvis[a][b]){
                color++;
                f(a,b);
        }
        cout<<ans[hasvis[a][b]]<<endl;
    }
    return 0;
}
